"use client";

import {
  Alert,
  AlertIcon,
  AlertTitle,
  Box,
  Button,
  Center,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Popover,
  PopoverArrow,
  PopoverBody,
  PopoverContent,
  PopoverFooter,
  PopoverTrigger,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import MacroNameEditor from "./MacroNameEditor";
import { useState } from "react";
import { MacroList, MacroAction } from "@/src/types/types.v1";
import CreateMacroName from "./CreateMacroName";
import SelectMacroType from "./SelectMacroType";
import MacroEditorV2 from "./MacroEditorV2";
import { useTranslation } from "@/src/i18n";

function CreateMacroList({
  onClose,
  onSave,
  checkName,
}: {
  onClose: () => void;
  onSave: (macro: MacroList) => void;
  checkName: (name: string) => boolean;
}) {
  const [macro, setMacro] = useState<MacroList>({
    name: "",
    type: -1,
    actions: [],
  });

  const [isSave, setIsSave] = useState(false);
  const exitMacroBtn = () => {
    if (isSave) {
      onClose();
    } else {
      cancelDlg.onOpen();
    }
  };

  const saveMacroList = () => {
    setIsSave(true);
    if (macro.name.length > 0) {
      onSave(macro);
    }
  };

  const [startRecord, setStartRecord] = useState(false);

  const handleNameChange = (name: string) => {
    setMacro((prev) => ({
      ...prev,
      name,
    }));
  };

  const addAction = (action: MacroAction) => {
    setMacro((prev) => ({
      ...prev,
      actions: [...prev.actions, action],
    }));
  };

  const cancelDlg = useDisclosure();
  const resetDlg = useDisclosure();

  const toast = useToast();
  const { t } = useTranslation("");
  return (
    <div className="fixed w-screen h-screen top-0 left-0 z-50 bg-[#000000]/90 backdrop-blur-[32px]">
      <Box className="flex flex-col h-full">
        <Box className="flex justify-between px-[40px] py-4 border-b border-[#eeeeee] items-center">
          <MacroNameEditor
            name={macro.name}
            onChange={(name) => {
              setMacro({ ...macro, name });
            }}
            checkName={checkName}
            isDisabled={startRecord}
            visibility={macro.name && macro.type != -1 ? "visible" : "hidden"}
          />
          <Box className="flex justify-end gap-4">
            <Button
              variant={"outline"}
              className="!text-[#0066ff] !border-[#0066ff]"
              isDisabled={startRecord}
              onClick={() => {
                saveMacroList();
                toast({
                  title: t("saveSuccess"),
                  status: "success",
                  duration: 2000,
                  position: "top",
                  render: () => (
                    <Alert
                      status="success"
                      border={"1px solid #0066FF33"}
                      w={"fit-content"}
                      borderRadius={"4px"}
                    >
                      <AlertIcon className="!text-blue-1" />
                      <AlertTitle>{t("saveSuccess")}</AlertTitle>
                    </Alert>
                  ),
                });
              }}
              visibility={macro.name && macro.type != -1 ? "visible" : "hidden"}
            >
              {t("save")}
            </Button>

            <Popover>
              {({ isOpen, onClose }) => (
                <>
                  <PopoverTrigger>
                    <Button
                      variant={"outline"}
                      className="bg-black"
                      isDisabled={startRecord}
                      visibility={
                        macro.name && macro.type != -1 ? "visible" : "hidden"
                      }
                    >
                      {t("reset")}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="!right-[-40px]">
                    <PopoverArrow />
                    <PopoverBody>
                      {" "}
                      <p className="text-white-3 text-center py-6">
                        {t("resetMarco")}
                      </p>
                      <Box className="flex gap-2 justify-center">
                        <Button
                          className="!bg-red-600 !text-white !px-3  hover:!bg-red-600/90 !font-normal !rounded-[8px]"
                          onClick={() => {
                            setMacro({ ...macro, actions: [] });
                            onClose();
                            toast({
                              title: t("haveReset"),
                              status: "success",
                              duration: 2000,
                              position: "top",
                              render: () => (
                                <Alert
                                  status="success"
                                  border={"1px solid #0066FF33"}
                                  w={"fit-content"}
                                  borderRadius={"4px"}
                                >
                                  <AlertIcon className="!text-blue-1" />
                                  <AlertTitle>{t("haveReset")}</AlertTitle>
                                </Alert>
                              ),
                            });
                          }}
                        >
                          {t("reset")}
                        </Button>
                        <Button
                          variant="ghost"
                          className="border border-gray-300 !font-normal !rounded-[8px]"
                          onClick={() => onClose()}
                        >
                          {t("cancel")}
                        </Button>
                      </Box>
                    </PopoverBody>
                  </PopoverContent>
                </>
              )}
            </Popover>

            <Button
              variant={"outline"}
              className="bg-[#0066ff]"
              isDisabled={startRecord}
              onClick={() => exitMacroBtn()}
            >
              {t("exitMacro")}
            </Button>
          </Box>
        </Box>
        <Box className="flex-1">
          {macro.name == "" && (
            <CreateMacroName
              onSumbit={(name) => setMacro({ ...macro, name })}
            />
          )}
          {macro.name != "" && macro.type == -1 && (
            <SelectMacroType
              onChange={(type) => setMacro({ ...macro, type })}
            />
          )}
          {macro.name != "" && macro.type != -1 && (
            <MacroEditorV2
              macro={macro}
              onChange={(macro) => setMacro({ ...macro })}
              onRecord={(start) => setStartRecord(start)}
            />
          )}
        </Box>
      </Box>
      <Modal
        isOpen={resetDlg.isOpen}
        onClose={resetDlg.onClose}
        size="sm"
        isCentered
      >
        <ModalOverlay />
        <ModalContent sx={{ color: "white" }}>
          <ModalBody>
            <p className="text-white-3 text-center pt-8">{t("resetMarco")}</p>
          </ModalBody>

          <ModalFooter className="gap-2">
            <Button
              className="!bg-red-600 !text-white !px-3  hover:!bg-red-600/90 !font-normal !rounded-[8px]"
              onClick={() => {
                setMacro({ ...macro, actions: [] });
                resetDlg.onClose();
                toast({
                  title: t("haveReset"),
                  status: "success",
                  duration: 2000,
                  position: "top",
                  render: () => (
                    <Alert
                      status="success"
                      border={"1px solid #0066FF33"}
                      w={"fit-content"}
                      borderRadius={"4px"}
                    >
                      <AlertIcon className="!text-blue-1" />
                      <AlertTitle>{t("haveReset")}</AlertTitle>
                    </Alert>
                  ),
                });
              }}
            >
              {t("reset")}
            </Button>
            <Button
              variant="ghost"
              className="border border-gray-300 !font-normal !rounded-[8px]"
              onClick={resetDlg.onClose}
            >
              {t("cancel")}
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
      <Modal
        isOpen={cancelDlg.isOpen}
        onClose={cancelDlg.onClose}
        size="lg"
        isCentered
      >
        <ModalOverlay />
        <ModalContent sx={{ color: "white" }}>
          <ModalHeader>{t("tips")}</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            <p className="text-white-3 text-center mb-2">{t("isSave")}</p>
          </ModalBody>

          <ModalFooter className="gap-2 !justify-center">
            <Button
              className="!bg-[#006BEE] !text-white !px-3 hover:!bg-[#0066FF]/90 !font-normal !rounded-[8px]"
              onClick={() => {
                saveMacroList();
                cancelDlg.onClose();
                toast({
                  title:
                    macro.name.length > 0 ? t("saveSuccess") : t("saveFail"),
                  status: macro.name.length > 0 ? "success" : "error",
                  duration: 2000,
                  position: "top",
                  render: () => (
                    <Alert
                      status="success"
                      border={"1px solid #0066FF33"}
                      w={"fit-content"}
                      borderRadius={"4px"}
                    >
                      <AlertIcon className="!text-blue-1" />
                      <AlertTitle>
                        {macro.name.length > 0
                          ? t("saveSuccess")
                          : t("saveFail")}
                      </AlertTitle>
                    </Alert>
                  ),
                });
                onClose();
              }}
            >
              {t("saveExit")}
            </Button>
            <Button
              className="border border-blue-1 !text-blue-1 !bg-transparent !font-normal !rounded-[8px]"
              onClick={() => {
                cancelDlg.onClose();
                onClose();
              }}
            >
              {t("directExit")}
            </Button>
            <Button
              variant="ghost"
              className="border border-gray-300  !font-normal !rounded-[8px]"
              onClick={cancelDlg.onClose}
            >
              {t("cancel")}
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </div>
  );
}

export default CreateMacroList;
